package com.bro.person.generator;

import org.apache.commons.collections.CollectionUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * swallow
 */
public class XMLUtil {

	private static final Logger logger = LoggerFactory.getLogger(XMLUtil.class);

	/**
	 * 动态修改MybatisGenerator需要生成的表名
	 *
	 * @return
	 * @throws DocumentException
	 */
	@SuppressWarnings("uncheck")
	public static void updateMybatisGeneratorXML(String[] tableNames) throws Exception {

		logger.debug("[XMLUtil][updateMybatisGeneratorXML]entering,tableNames:{}", tableNames);

		String xmlFilePath = ClassLoader.getSystemResource("generatorConfig.xml").getPath();
		SAXReader reader = new SAXReader();
		// 忽略DTD验证，否则会有联网超时问题
		reader.setEntityResolver(new IgnoreDTDEntityResolver());
		Document document = reader.read(new File(xmlFilePath));
		// 获取文档的根元素
		Element rootElement = document.getRootElement();
		Element contextElement = rootElement.element("context");

		// 获取根节点下的所有table子元素
		List<Element> elements = contextElement.elements("table");
		// 循环删除所有子元素
		if (CollectionUtils.isNotEmpty(elements)) {
			for (Element element : elements) {
				element.detach();
			}
		}
		for (String tableName : tableNames) {
			Element tableElement = contextElement.addElement("table");
			tableElement.addAttribute("schema", "wx");
			tableElement.addAttribute("tableName", tableName);
			tableElement.addAttribute("domainObjectName", CamelCaseUtil.toCapitalizeCamelCase(tableName));
		}

		// 指定文件输出的位置
		FileOutputStream out = new FileOutputStream(xmlFilePath);
		// 指定文本的写出的格式：
		// 漂亮格式：有空格换行
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		// 1.创建写出对象
		XMLWriter writer = new XMLWriter(out, format);
		// 2.写出Document对象
		writer.write(document);
		// 3.关闭流
		writer.close();
	}

	/**
	 * 忽略DTD验证
	 */
	static class IgnoreDTDEntityResolver implements EntityResolver {
		@Override
		public InputSource resolveEntity(String publicId, String systemId) {
			return new InputSource(new ByteArrayInputStream("".getBytes()));
		}
	}
}
